package com.xxl.sso.server.config;

import com.xxl.sso.core.store.SsoLoginStore;
import com.xxl.sso.server.util.JedisUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @author xuxueli 2018-04-03 20:41:07
 */
@Configuration
public class XxlSsoCacheConfig implements InitializingBean, DisposableBean {

    @Value("${xxl.sso.redisAddress}")
    private String redisAddress;

    @Value("${xxl.sso.redis.expire.minute:1440}")
    private int redisExpireMinute;

    @Value("${xxl.sso.mysqlSubstitute:false}")
    private boolean mysqlSubstitute;

    @Value("${xxl.sso.cache.expireMinute:1440}")
    private int expireMinute;

    //超时时间
    private static int cacheExpireMinute = 1440;    // 1440 minute, 24 hour

    public static int getCacheExpireMinute() {
        return cacheExpireMinute;
    }

    public static void setCacheExpireMinute(int cacheExpireMinute) {
        if (cacheExpireMinute < 30) {
            XxlSsoCacheConfig.cacheExpireMinute = 30;
        }
        XxlSsoCacheConfig.cacheExpireMinute = cacheExpireMinute;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if(mysqlSubstitute){
            setCacheExpireMinute(expireMinute);
        }else{
            setCacheExpireMinute(redisExpireMinute);
            JedisUtil.init(redisAddress);
        }
    }

    @Override
    public void destroy() throws Exception {
        if(!mysqlSubstitute){
            JedisUtil.close();
        }
    }

}
